package com.arvato.right.controller;

import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arvato.common.redis.RedisUtil;
import com.arvato.common.util.JsonUtil;
import com.arvato.common.util.MD5Util;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.minipro.bean.bean_dto.common.TreeBean;
import com.arvato.right.bean.bean_vo.WxworkRightUserVo;
import com.arvato.right.service.WxworkRightResourceService;
import com.arvato.right.service.WxworkRightUserService;


/**
 * Describe：处理用户登录和注册的controller
 * 
 * @author smallking
 *
 *  2017年12月28日
 */
@Controller
@RequestMapping("/admin/login")
public class AdminLoginController {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private JsonUtil jsonUtil;
	
	@Autowired
	private WxworkRightUserService wxworkRightUserService;
	
	@Autowired
	private WxworkRightResourceService wxworkRightResourceService;
	
	/**
	 * 校验用户登录
	 * @param account
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/in")
	public Result checkLogin(String account, String password, HttpServletRequest req, HttpServletResponse resp){
		System.out.println("登录开始");
		if(account == null || account.trim().equals("") || password == null || password.trim().equals("")){ 
			System.out.println("账号或密码不能为空");
			return Result.fail("账号或密码不能为空");
		}
		Query query = new Query();
		query.put("account", account);
		System.out.println("查询开始");
		// 确认参数合法之后
		List<WxworkRightUserVo> userList = wxworkRightUserService.listUserByQuery(query);
		if(userList == null || userList.size() == 0){
			System.out.println("该用户不存在");
			return Result.fail("该用户不存在");
		}
		WxworkRightUserVo user = userList.get(0);
		password = MD5Util.md5(password);
		if(!password.equals(user.getPassword())){
			System.out.println("密码不正确");
			return Result.fail("密码不正确");
		}
		if(!user.getStatus().equals(1)){
			return Result.fail("用户状态异常");
		}
		// 登录成功之后，将其权限信息（菜单显示项和接口URl调用项）查出来，放到session中
		List<TreeBean> menuList = wxworkRightResourceService.getTreeByUserId(user.getUserId());
		user.setMenuList(menuList);
		// 登录成功之后 将用户信息存储在redis里面 用户的id为key 详情为value
		String key = MD5Util.md5(user.getUserId());
		redisUtil.set(key, jsonUtil.obj2String(user), 7200);
		// 将token放在cookie里面返回去
        Cookie tokenCookie = new Cookie("token", key);
        // 如果不设置使用时间，那么将取不到Cookie的值
        tokenCookie.setMaxAge(7200);
        // 一旦设置了cookie的路径，就只能通过这一个路径才能获取到cookie信息
        tokenCookie.setPath("/");
        // 服务器把cookie响应给客户端，所有的cookie对象，都会在服务器端创建，通过http响应给客户端(浏览器)
        resp.addCookie(tokenCookie);
		System.out.println("登录成功");
		return Result.success(user);
	}

	/**
	 * 退出登录
	 * @param req
	 * @param resp
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/out")
	public Result loginOut(HttpServletRequest req, HttpServletResponse resp){
		System.out.println("----------退出登录-----------");
		Cookie[] cookies = req.getCookies();
		if(cookies != null && cookies.length != 0) {
			for(Cookie cookie : cookies){
	    		if(cookie.getName().equals("token") && cookie.getValue() != null) {
	    			redisUtil.set(cookie.getValue(), "", 1);
	    		}
	    	}
		}
		Cookie cookie = new Cookie("token", "");
		cookie.setMaxAge(0);//设置为0为立即删除该Cookie
		cookie.setPath("/");//删除指定路径的cookie,不设置该路径，默认为删除当前路径Cookie
		resp.addCookie(cookie);
		return Result.success("退出登录");
	}
	
	/**
	 * 查看当前登录人的信息
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/user/detail")
	public Result userDetail(HttpServletRequest req){
		Object user = req.getSession().getAttribute("loginUser");
		return Result.success(user);
	}
	
}

